from datetime import datetime
import requests

class OrderSubmitter:
    def submit_order(self, ticket_info):
        """订单提交流程"""
        # 1. 生成预订请求
        reserve_data = self._build_reserve_data(ticket_info)
        
        # 2. 提交预订单（含智能重试）
        max_retries = 3
        retry_count = 0
        while retry_count < max_retries:
            reserve_response = self._post(SUBMIT_ORDER_URL, reserve_data)
            if reserve_response['status']:
                break
            retry_count += 1
            if retry_count < max_retries:
                time.sleep(2)  # 重试间隔2秒
        if not reserve_response['status']:
            raise OrderError(f"预订单提交失败，已重试{max_retries}次")
        
        # 3. 获取排队信息
        queue_info = self._get_queue_count(ticket_info)
        
        # 4. 确认订单
        confirm_data = self._build_confirm_data(queue_info)
        confirm_response = self._post(CONFIRM_URL, confirm_data)
        
        return self._parse_order_result(confirm_response)
    
    def _build_reserve_data(self, ticket):
        """构造预订请求参数"""
        secret_str = self.parse_secret_str(ticket['secret'])  # 解析加密字符串
        return {
            'secretStr': secret_str,
            'train_date': ticket['date'].strftime("%Y-%m-%d"),
            'back_train_date': datetime.now().strftime("%Y-%m-%d"),
            'tour_flag': 'dc',
            'purpose_codes': 'ADULT',
            'leftTicketStr': ticket['leftTicket'],
            'key_check_isChange': ticket['key_check'],
            'choose_seats': self._select_seats(ticket),  # 根据配置选择座位
            'seatDetailType': '000',
            'whatsSelect': '1'
        }
    
    def _post(self, url, data):
        # 实际项目中需要处理网络请求和错误
        response = requests.post(url, json=data)
        return response.json()
    
    def parse_secret_str(self, secret):
        # 解析加密字符串的逻辑，根据实际接口调整
        return secret
    
    def _get_queue_count(self, ticket_info):
        # 获取排队信息的逻辑
        return {'queue_count': 10}
    
    def _build_confirm_data(self, queue_info):
        # 构造确认订单参数
        return {'queue_count': queue_info['queue_count']}
    
    def _parse_order_result(self, response):
        # 解析订单结果
        return response.get('order_id', None)

class OrderError(Exception):
    pass